package com.sunnay.web;

import com.sunnay.vo.auth.SystemUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ContextHelper {

    public final static String USER_INFO = "_client_";
    //默认存活一个月
    public final static int SESSION_MAX_INACTIVE_INTERVAL_DEFAULT=60*60*24*30;

    private static SystemUser EMPTY_USER = new SystemUser();

    /**
     * 获取当前环境下的用户信息
     * @return
     */
    public static SystemUser getSystemUser() {
        HttpSession session = getSession(false);
        if (session!= null) {
            SystemUser systemUser = (SystemUser) session.getAttribute(USER_INFO);
            if (systemUser == null) {
                return EMPTY_USER;
            }
            return systemUser;
        }
        return EMPTY_USER;
    }

    /**
     * 清除用户信息
     */
    public static void clearSystemUser() {
        HttpSession session = getSession(false);
        if (session != null) {
            session.setMaxInactiveInterval(0);
            session.invalidate();
        }
    }

    /**
     * 清除用户信息
     */
    public static void clearSystemUser(HttpSession session) {
        if (session != null) {
            session.setMaxInactiveInterval(0);
            session.invalidate();
        }
    }

    /**
     * 向session设置值
     * @param name
     * @param value
     */
    public static void setSessionAttribute(String name, Object value) {
        getSession(true).setAttribute(name,value);
    }

    /**
     * 获取request对象
     * @return
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
    }

    /**
     * 获取返回对象
     * @return
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取session对象
     * @return
     */
    public static HttpSession getSession(boolean flag) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return request.getSession(flag);
    }
}
